<template>
<div class="container">
  <van-nav-bar
      title="爱心捐"
      left-text="返回"
      left-arrow
      fixed
      @click-left="onClickLeft"
  />
  <image-crop
      :uploadLoading="uploadLoading"
      :imgUrl="ruleForm.whitePhoneUrl"
      @before-upload="beforeRead"
      @after-upload="cropUpload"
  ></image-crop>
</div>
</template>

<script>
import imageCrop from "../components/utils/imgCropper";
export default {
  name: "Give",
  components:{imageCrop},
  data(){
    return{
      uploadLoading:false,
      imgUrl:'',
      ruleForm:{
        whitePhoneUrl:''
      }
    }
  },
  methods:{
    onClickLeft() {
      this.$router.back()
    },
    beforeRead(file, callback) {
      const isImgType = file.type === "image/jpeg" || file.type === "image/png";
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isImgType) {
        this.$toast("上传图片只能是 JPG或PNG 格式!");
        callback(false);
        return false;
      }
      if (!isLt10M) {
        this.$toast("上传图片大小不能超过 10MB!");
        callback(false);
        return false;
      }
      callback(true);
      return true;
    },
    afterRead(file) {
      file.status = "uploading";
      file.message = "上传中...";
      let param=new FormData()
      param.append("file",file.file)
      const config={
        headers:{
          "Content-Type":"multipart/form-data"
        }
      }
      this.$http.post('/goods/uploadImage',param,config).then((res) => {
        if (res.status == 200) {
          file.status = "done";
          file.message = "上传完成";
          this.ruleForm.whitePhotoId = res.data;
        } else {
          file.status = "failed";
          file.message = "上传失败";
          this.$toast(res.data);
        }
      });
    },
    cropUpload(file) {
      this.uploadLoading = true;
      let param=new FormData()
      param.append("file",file.file)
      const config={
        headers:{
          "Content-Type":"multipart/form-data"
        }
      }

      this.$http.post('/goods/uploadImage',param,config).then((res) => {

        if (res.status == 200) {
          this.uploadLoading = false;
          this.ruleForm.whitePhotoId = res.data;
          this.imgUrl=res.data.result.goods_img
        } else {
          this.uploadLoading = false;
          this.$toast(res.data);
        }
      });
    }
  }
}
</script>

<style scoped>
.container{
  padding-top: 50px;
}
</style>
